﻿#region using
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using AifMessageHeaderEditor.Lib.Data.MessageDocument;
using System.Xml.Schema;
using AifMessageHeaderEditor.Lib.Properties;
#endregion

namespace AifMessageHeaderEditor.Lib.File
{
    /// <summary>
    /// Contains the instance of the <c>MessageDocument</c> and the file-information.
    /// </summary>
    public partial class MessageFile : FileBase
    {
        #region FileInformation

        private MessageDocument _mhi = new MessageDocument();

        public MessageDocument MessageFileInformation
        {
            get { return _mhi; }
        }

        #endregion

        #region MessageFile-Singleton

        static MessageFile _mf = new MessageFile();

        /// <summary>
        /// The instance of the <c>MessageFile</c>
        /// </summary>
        static public MessageFile Instance
        {
            get
            {
                return _mf;
            }
        }

        #endregion

        #region validating

        /// <summary>
        /// Tries to load the Xml-file. <c>Exception</c> if not validated.
        /// </summary>
        /// <param name="filename"></param>
        public override bool ValidateFile(string filename)
        {
            bool isValid = true;
            XmlDocument xmlMessage = new XmlDocument();

            xmlMessage.Load(filename);
            _messageList.Clear();
            StringReader axMessageReader = new StringReader(Resources.Message);
            //StringReader axEntityKeyListReader = new StringReader(Ax2009.EntityKeyList);
            //StringReader axQueryCriteriaReader = new StringReader(Ax2009.QueryCriteria);
            XmlSchema schema = XmlSchema.Read(axMessageReader, null);
            xmlMessage.Schemas.Add(schema);
            xmlMessage.Validate(new ValidationEventHandler(ValidationCallBack),
                AppCommon.SelectXmlHeaderNode(xmlMessage, string.Empty));

            if (_messageList.Count > 0)
            {
                isValid = false;
            }
            _isValid = isValid;

            return isValid;
        }

        private void ValidationCallBack(Object sender, ValidationEventArgs args)
        {
            _messageList.Add(args.Message);
        }

        #endregion

        #region Notification

        protected override void NotifyChanges()
        {
            XmlFile.NotifyChanges();
        }

        #endregion
    }
}